<?php
/**
 * 雅思课程
 * Created by PhpStorm.
 * User: yanni
 */
namespace app\modules\cn\controllers;
use app\libs\Write;
use app\modules\cn\models\ExerciseCorrection;
use yii;
use UploadFile;
use app\libs\IeltsController;
use app\modules\cn\models\User;
use app\modules\cn\models\Content;
use app\modules\content\models\ContentTag;
use app\modules\cn\models\UserDiscuss;
use app\modules\cn\models\RankingAll;
use app\modules\cn\models\RankingOrder;
use app\modules\cn\models\ExerciseList;
use app\modules\cn\models\ExerciseCategory;
use app\modules\cn\models\ExerciseTopic;
use app\modules\cn\models\ExerciseLevel;
use app\modules\cn\models\ExerciseType;
use app\modules\cn\models\ExerciseListDetail;
use app\modules\cn\models\TestResult;
use app\modules\cn\models\ExerciseStatus;
use app\modules\cn\models\ExerciseResult;
use app\modules\exercise\models\IeltsTestSet;
use app\modules\exercise\models\ExerciseBanner;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class ExerciseController extends IeltsController
{
    public $enableCsrfValidation = false;
    public $layout = 'exercise';

    public function actionExerciseTopic()
    {
        return $this->render('exercise-topic');
    }

    /**
     * @Title  [做题练习新首页]
     * @Author Don
     * @Date   2021-04-20
     * @return [type]
     */
    public function actionPractice()
    {
        // // $userId = Yii::$app->session->get('userId');
        // $uid = Yii::$app->session->get('uid');
        // // 晚上10.00-次日8.00，后台填的数据为0
        // $night = strtotime(date('Y-m-d 22:00:00'));
        // $morning = strtotime(date('Y-m-d 08:00:00', strtotime('+1 days')));

        // if (time() > $night && time() < $morning) {
        //     $set_doing_num = $set_today_num = $set_heap_num = $set_already_num = 0;
        // } else {
        //     $tmp1 = IeltsTestSet::findOne(1);
        //     $set_doing_num = $tmp1->num;
        //     $tmp2 = IeltsTestSet::findOne(2);
        //     $set_today_num = $tmp2->num;
        //     $tmp3 = IeltsTestSet::findOne(3);
        //     $set_heap_num = $tmp3->num;
        //     $tmp4 = IeltsTestSet::findOne(4);
        //     $set_already_num = $tmp4->num;
        // }
        // // 正在做题人数
        // $doing_num = rand(8,20);
        // // 今日做题人数
        // $start_time = strtotime(date('Y-m-d').' 00:00:00');
        // $end_time = strtotime(date('Y-m-d').' 23:59:59');
        // $today_num = count(RankingAll::find()->select('userid')->where(['between', 'createtime', $start_time, $end_time])->distinct()->asArray()->all());
        // // 累积做题人数
        // $heap_num = count(RankingAll::find()->select('userid')->distinct()->asArray()->all());
        // // 已助考雅思人数
        // $already_num = 0;
        // // 所有剑雅真题数
        // $all_jianya_num = count(ExerciseListDetail::find()->all());
        // // 用户做题数量
        // $sql = "select userid,count(*) as num from `x2_ielts_test_result` group by userid";
        // $all_user_do = Yii::$app->db->createCommand($sql)->queryAll();
        // foreach ($all_user_do as $v) {
        //     if ($v['num'] >= $all_jianya_num) {
        //         $already_num++;
        //     }
        // }

        // // 累计做题数
        // $exercise_num = 0;
        // // 今日做题数
        // $today_exercise_num = 0;
        // // 已累计学习天数
        // $study_days = 0;

        // // 烤鸭排行榜
        // $ielts_rank = RankingOrder::find()->where(['typeid' =>0])->orderBy('order DESC')->andWhere(['not', ['userid' => null]])->andWhere(['!=', 'order', 0])->distinct()->limit(7)->asArray()->All();
        // foreach ($ielts_rank as $k => $v) {
        //     $id = $v['userid'];
        //     $name = User::find()->where(['id'=>$id])->asArray()->One();
        //     $ielts_rank[$k]['userName'] = $name['nickname'] ? $name['nickname'] : $name['userName'];
        // }
        // $userInfo = [];
        // if ($uid) {
        //     // 烤鸭榜更新
        //     $model = new ExerciseList();
        //     $model->getlistentestorder(0);
        //     // 用户信息
        //     $userInfo = User::find()->where(['uid' =>$uid])->asArray()->One();
        //     $userId = $userInfo['id'];
        //     // 正确条数
        //     $true_exercise = count(RankingAll::find()->where(['userid'=>$userId,'result'=>1])->asArray()->All());
        //     // 错误条数
        //     $false_exercise = RankingAll::find()->where(['userid'=>$userId,'result'=>0])->asArray()->All();
        //     // 总共条数
        //     $exercise_num = count(RankingAll::find()->where(['userid' =>$userId])->andWhere(['not', ['testid' => null]])->asArray()->All());
        //     // f_d($exercise_num);
        //     // 做题天数
        //     $daycode = RankingAll::find()->where(['userid' =>$userId])->orderBy('createtime ASC')->asArray()->one();
        //     if (!empty($daycode)) {
        //         $timecode = time();
        //         $times =strtotime(date('Y-m-d',$daycode['createtime']));
        //         $code = $timecode - $times;
        //         $study_days = ceil($code/3600/24);
        //     } else {
        //         $study_days = 0;
        //     }

        //     $start_time = strtotime(date('Y-m-d 00:00:00',time()));
        //     $end_time = strtotime(date('Y-m-d 23:59:59',time()));
        //     // 统计今日做题数量
        //     $today_exercise_num = count(RankingAll::find()->where(['between', 'createtime',$start_time, $end_time])->andWhere(['userid'=>$userId])->andWhere(['not', ['testid' => null]])->asArray()->All());
        // }
        // $this->title = '申友雅思在线_专注雅思培训_雅思真题练习';
        // $this->description = '申友雅思在线是上海雅思培训机构，针对不同基础的学生，提供雅思培训班，最新雅思真题、雅思考试备考资料，只为雅思提分，申友雅思在线。';
        // $this->keywords = '雅思培训,雅思真题练习,雅思考试,雅思备考';
        // return $this->render('new_index', [
        //     'doing_num' => $doing_num + $set_doing_num,
        //     'today_num' => $today_num + $set_today_num,
        //     'heap_num' => $heap_num + $set_heap_num,
        //     'already_num' => $already_num + $set_already_num,
        //     'userInfo' => !empty($userInfo) ? $userInfo : [],
        //     'exercise_num' => $exercise_num,
        //     'today_exercise_num' => $today_exercise_num,
        //     'study_days' => $study_days,
        //     'ielts_rank' => $ielts_rank
        // ]);
        $userId = Yii::$app->session->get('userId');
        // if(!$userId){
        //     $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
        //     return $this->redirect($url);
        // }
        $model = new ExerciseList();
        // 分类
        $category = Yii::$app->request->get('category', 'all');
        if ($category == 'all') { // 全部剑雅
            $cate_id_arr = array(413, 424, 435);

            $data = $model->getListenList($cate_id_arr,1);
            // f_d($data);
            // 没有就默认cate_id=418
            $cate_id = intval(Yii::$app->request->get('cate_id', 418));

            // 剑雅对应分类下的题目
            $cate_list = $data[1][0][$cate_id];

            $list = [];
            if ($cate_list) {
                // 拆分 Test-Section
                if (in_array($cate_id, [420,421,422,423,700])) {
                    foreach ($cate_list as $key => $value) {
                        $tmp = explode('-', $value['name']);
                        $cate_list[$key]['test_name'] = $tmp[1];
                        $cate_list[$key]['section_name'] = $tmp[2];
                    }
                    $list = $cate_list;
                } else {
                    foreach ($cate_list as $key => $value) {
                        $tmp = explode('-', $value['name']);
                        $cate_list[$key]['test_name'] = $tmp[0];
                        $cate_list[$key]['section_name'] = $tmp[1];
                    }
                    $list = $cate_list;
                }
            }

            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }
            $category_id = '';
            $datelist = $data[0][0];

            // 逻辑删除剑雅4、5、6、7、15
//            foreach ($datelist as $key => $value) {
//                if (in_array($value['cate_id'], [414,415,416,417,701])) {
//                    unset($datelist[$key]);
//                }
//            }

        } elseif ($category == 'level') { // 难度
            // 所有难度包含的题
            $datelist = ExerciseLevel::getLevel(408);
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }


            $cate_id = 0;
        } elseif ($category == 'topic') { // 话题
            // 所有话题包含的题
            $datelist = ExerciseTopic::getTopic(408); // 听力所有话题
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }

            $cate_id = 0;
        } elseif ($category == 'type') { // 题型
            $cate_id = intval(Yii::$app->request->get('cate_id', 425));
            // 所有题型包含的题
            $datelist = ExerciseType::getType(408); // 听力所有题型
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }
        }

        // 右边banner
        $banner = ExerciseBanner::find()->where(['typeid'=>1])->asArray()->one();

        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';

        return $this->render('new_index', [
            'type' =>1,
            'typename' =>'听力练习',
            'banner' => $banner,
            'datelist' => $datelist,
            'list' => $res,
            'cate_id' => $cate_id,
            'category' => $category,
            'category_id' => $category_id
        ]);
    }

    /**
     * @Title  [获取我的做题记录]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionGetExerciseRecord()
    {
        $userId = Yii::$app->session->get('userId');
        if (!$userId) {
            die(json_encode(['message' => '请登录后查看！', 'code' => 0]));
        }
        $page = Yii::$app->request->get('page', 1);
        $page_size = 7; // 每页条数

        $sql_count = "select DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') as createtime from x2_ielts_test_result where userid =$userId group by DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') order by id desc";
        $total_num = count(Yii::$app->db->createCommand($sql_count)->queryAll());

        $page_total = ceil($total_num / $page_size); //总页数
        if ($page > 0) {
            $page_start = ($page-1)*$page_size;
        }else{
            $page_start = 0;
        }
        $sql = "select DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') as createtime from x2_ielts_test_result where userid =$userId group by DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d') order by id desc limit $page_start, $page_size";
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        if ($data) {
            $dates = [];
            foreach ($data as $key => $value) {
                // listen 1
                $sql_1 = "select * from x2_ielts_test_result where DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d %H:%i:%s') between '".$value['createtime']." 00:00:00' and '".$value['createtime']." 23:59:59' and userid =$userId and typeid=1";
                $tmp_1 = Yii::$app->db->createCommand($sql_1)->queryAll();
                // f_d($tmp_1);
                $listen_total = count($tmp_1);
                $listen_correct = 0;
                if ($tmp_1) {
                    foreach ($tmp_1 as $k1 => $v1) {
                        if ($v1['result'] == 1) {
                            $listen_correct++;
                        }
                    }

                }
                $data[$key]['listen_total'] = $listen_total;
                $data[$key]['listen_correct'] = $listen_correct;

                // read 2
                $sql_2 = "select * from x2_ielts_test_result where DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d %H:%i:%s') between '".$value['createtime']." 00:00:00' and '".$value['createtime']." 23:59:59' and userid =$userId and typeid=2";
                $tmp_2 = Yii::$app->db->createCommand($sql_2)->queryAll();

                $read_total = count($tmp_2);
                $read_correct = 0;
                if ($tmp_2) {
                    foreach ($tmp_2 as $k2 => $v2) {
                        if ($v2['result'] == 1) {
                            $read_correct++;
                        }
                    }
                    // f_d($listen_correct);
                }
                $data[$key]['read_total'] = $read_total;
                $data[$key]['read_correct'] = $read_correct;

                // write 3（写作没有成绩）
                $data[$key]['write_total'] = 0;
                $data[$key]['write_correct'] = 0;

                // speak 4
                $sql_4 = "select * from x2_ielts_test_result where DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d %H:%i:%s') between '".$value['createtime']." 00:00:00' and '".$value['createtime']." 23:59:59' and userid =$userId and typeid=4";
                $tmp_4 = Yii::$app->db->createCommand($sql_4)->queryAll();

                $speak_total = count($tmp_4);
                $speak_correct = 0;
                if ($tmp_4) {
                    foreach ($tmp_4 as $k4 => $v4) {
                        if ($v4['result'] == 1) {
                            $speak_correct++;
                        }
                    }

                }
                $data[$key]['speak_total'] = $speak_total;
                $data[$key]['speak_correct'] = $speak_correct;

            }
            $data = array_column($data, NULL, 'createtime');

            foreach ($data as $k => $v) {
                // listen
                $listen_rate = $v['listen_correct'] == 0 ? 0 : (sprintf("%.2f", $v['listen_correct']/$v['listen_total'])) * 100;
                $data[$k]['listen_score'] = RankingAll::score($listen_rate);
                // read
                $read_rate = $v['read_correct'] == 0 ? 0 : (sprintf("%.2f", $v['read_correct']/$v['read_total'])) * 100;
                $data[$k]['read_score'] = RankingAll::score($read_rate);
                // speak
                $speak_rate = $v['speak_correct'] == 0 ? 0 : (sprintf("%.2f", $v['speak_correct']/$v['speak_total'])) * 100;
                $data[$k]['speak_score'] = RankingAll::score($speak_rate);
                // write
                $data[$k]['write_score'] = '-';

                $arr = [$data[$k]['listen_score'] , $data[$k]['read_score'] , $data[$k]['speak_score']];
                $chu = count(array_filter($arr));

                $data[$k]['total'] = $chu?RankingAll::formatScore(($data[$k]['listen_score'] + $data[$k]['read_score'] + $data[$k]['speak_score'])/$chu):0;
            }

            die(json_encode(['message' => 'success', 'code' => 1, 'data' => $data , 'page'=>$page, 'page_size'=>$page_size, 'page_total'=>$page_total]));
        } else {
            die(json_encode(['message' => '未找到记录', 'code' => 0]));
        }
    }

    /**
     * @Title  [听-剑雅首页]
     * @Author Don
     * @Date   2021-04-19
     * @return [type]
     */
    public function actionListen()
    {
        $userId = Yii::$app->session->get('userId');
        // if(!$userId){
        //     $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
        //     return $this->redirect($url);
        // }
        $model = new ExerciseList();
        // 分类
        $category = Yii::$app->request->get('category', 'all');
        if ($category == 'all') { // 全部剑雅
            $cate_id_arr = array(413, 424, 435);

            $data = $model->getListenList($cate_id_arr,1);

            // 删除听力 剑雅4，剑雅5，剑雅6，剑雅7，剑雅15
//            unset($data[0][0][0]);
//            unset($data[0][0][1]);
//            unset($data[0][0][2]);
//            unset($data[0][0][3]);
//            unset($data[0][0][11]);
            // f_d($data);
            // 没有就默认cate_id=418
            $cate_id = intval(Yii::$app->request->get('cate_id', 418));

            // 剑雅对应分类下的题目
            $cate_list = $data[1][0][$cate_id];

            $list = [];
            if ($cate_list) {
                // 拆分 Test-Section
                if (in_array($cate_id, [420,421,422,423,700])) {
                    foreach ($cate_list as $key => $value) {
                        $tmp = explode('-', $value['name']);
                        $cate_list[$key]['test_name'] = $tmp[1];
                        $cate_list[$key]['section_name'] = $tmp[2];
                    }
                    $list = $cate_list;
                } else {
                    foreach ($cate_list as $key => $value) {
                        $tmp = explode('-', $value['name']);
                        $cate_list[$key]['test_name'] = $tmp[0];
                        $cate_list[$key]['section_name'] = $tmp[1];
                    }
                    $list = $cate_list;
                }
            }

            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }
            $category_id = '';
            $datelist = $data[0][0];

            // 逻辑删除剑雅4、5、6
//            foreach ($datelist as $key => $value) {
//                if (in_array($value['cate_id'], [414,415,416])) {
//                    unset($datelist[$key]);
//                }
//            }

        } elseif ($category == 'level') { // 难度
            // 所有难度包含的题
            $datelist = ExerciseLevel::getLevel(408);
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }


            $cate_id = 0;
        } elseif ($category == 'topic') { // 话题
            // 所有话题包含的题
            $datelist = ExerciseTopic::getTopic(408); // 听力所有话题
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }

            $cate_id = 0;
        } elseif ($category == 'type') { // 题型
            $cate_id = intval(Yii::$app->request->get('cate_id', 425));
            // 所有题型包含的题
            $datelist = ExerciseType::getType(408); // 听力所有题型
            $category_id = Yii::$app->request->get('category_id', 1);
            $list = $model->getListenListByCate($category, 413, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }
        }

        // 右边banner
        $banner = ExerciseBanner::find()->where(['typeid'=>1])->asArray()->one();

        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';
        switch (@$_GET['category'])
        {
            case 'all':$cate_seo_name = '全部剑雅';break;
            case 'type':$cate_seo_name = '按题型练';break;
            case 'topic':$cate_seo_name = '按话题练';break;
            case 'level':$cate_seo_name = '按难度练';break;
            default:$cate_seo_name = '全部剑雅';break;
        }
        return $this->render('new_index', [
            'type' =>1,
            'typename' =>'听力练习',
            'banner' => $banner,
            'datelist' => $datelist,
            'list' => $res,
            'cate_id' => $cate_id,
            'category' => $category,
            'category_id' => $category_id,
            'cate_seo_name' => $cate_seo_name
        ]);
    }

    /**
     * @Title  [说]
     * @Author Don
     * @Date   2021-04-19
     * @return [type]
     */
    public function actionSpeak()
    {
        $userId = Yii::$app->session->get('userId');
        // if(!$userId){
        //     $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
        //     return $this->redirect($url);
        // }
        $category = Yii::$app->request->get('category', 'all');
        if ($category == 'all') {
            $cate_id = Yii::$app->request->get('cate_id',546); // 默认剑雅8 546
            $cate_model = new ExerciseCategory();
            $datalist = $cate_model->getSpeakCateList($cate_id,1);
            // 删除剑雅5、剑雅6、剑雅7
//            unset($datalist[0]);
//            unset($datalist[1]);
//            unset($datalist[2]);
            $model = new ExerciseList();
            $cate_list = $model->getSpeakList($cate_id);
            $list = [];
            if ($cate_list) {
                foreach ($cate_list as $key => $value) {
                    $tmp = explode('-', $value['name']);
                    $cate_list[$key]['test_name'] = substr(trim($value['name']),0, -6);
                    $cate_list[$key]['part_name'] = substr(trim($value['name']), -5);
                }
                $list = $cate_list;
            }

            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }

        } elseif ($category == 'topic') {
            // code...
        }

        // 右边banner
        $banner = ExerciseBanner::find()->where(['typeid'=>4])->asArray()->one();

        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';
        return $this->render('new_index', [
            'type' =>4,
            'typename' =>'口语练习',
            'banner' => $banner,
            'datelist' => $datalist,
            'list' => $res,
            'cate_id' => $cate_id,
            'category' => $category
        ]);
    }

    /**
     * @Title  [读]
     * @Author Don
     * @Date   2021-04-19
     * @return [type]
     */
    public function actionRead()
    {
        $userId = Yii::$app->session->get('userId');

        // if(!$userId){
        //     $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
        //     return $this->redirect($url);
        // }
        $model = new ExerciseList();
        $category = Yii::$app->request->get('category', 'all');

        if ($category == 'all') { // 全部剑雅
            $cate_id_arr = array(462);

            $data = $model->getListenList($cate_id_arr,1);
            // 删除剑雅5、剑雅6、剑雅7
//            unset($data[0][0][0]);
//            unset($data[0][0][1]);
//            unset($data[0][0][2]);
            // 没有就默认cate_id=414
            $cate_id = intval(Yii::$app->request->get('cate_id', 469));

            // 剑雅对应分类下的题目
            $cate_list = $data[1][0][$cate_id];

            $list = [];
            if ($cate_list) {
                // 拆分 Test-Section
                foreach ($cate_list as $key => $value) {
                    $tmp = explode('-', $value['name']);
                    if (count($tmp) == 3) {
                        $cate_list[$key]['test_name'] = $tmp[1];
                        $cate_list[$key]['section_name'] = $tmp[2];
                    } else {
                        $cate_list[$key]['test_name'] = $tmp[0];
                        $cate_list[$key]['section_name'] = $tmp[1];
                    }

                }
                $list = $cate_list;
            }

            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }
            $category_id = '';
            $datelist = $data[0][0];
        } elseif ($category == 'level') { // 难度
            // 所有难度包含的题
            $datelist = ExerciseLevel::getLevel(462);

            $category_id = Yii::$app->request->get('category_id', 4);
            $list = $model->getReadListByCate($category, 462, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }


            $cate_id = 0;
        } elseif ($category == 'topic') { // 话题
            // 所有话题包含的题
            $datelist = ExerciseTopic::getTopic(462); // 阅读所有话题

            $category_id = Yii::$app->request->get('category_id', 12);
            $list = $model->getReadListByCate($category, 462, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }

            $cate_id = 0;
        } elseif ($category == 'type') { // 题型
            // 所有话题包含的题
            $datelist = ExerciseType::getType(462); // 阅读所有题型
            $category_id = Yii::$app->request->get('category_id', 6);
            $list = $model->getReadListByCate($category, 462, $category_id);

            $res = [];
            if ($list) {
                foreach ($list as $key => $value) {
                    if (array_key_exists($value['catName'], $res)) {
                        $res[$value['catName']][] = $value;
                    } else {
                        $res[$value['catName']][] = $list[$key];
                    }
                }
            }

            $cate_id = 0;
        }
        // 右边banner
        $banner = ExerciseBanner::find()->where(['typeid'=>2])->asArray()->one();

        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';

        return $this->render('new_index', [
            'type' =>2,
            'typename' =>'阅读练习',
            'banner' => $banner,
            'datelist' => $datelist,
            'list' => $res,
            'cate_id' => $cate_id,
            'category' => $category,
            'category_id' => $category_id
        ]);
    }

    /**
     * @Title  [写]
     * @Author Don
     * @Date   2021-04-19
     * @return [type]
     */
    public function actionWrite()
    {
        $userId = Yii::$app->session->get('userId');
        // if(!$userId){
        //     $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
        //     return $this->redirect($url);
        // }
        // 分类 all全部，topic话题
        $category = Yii::$app->request->get('category', 'all');
        if ($category == 'all') { // 全部剑雅
            // 默认分类id
            $cate_id_arr = array(512, 513, 514);
            // 没有就默认cate_id=515
            $cate_id = intval(Yii::$app->request->get('cate_id', 518));
            $model = new ExerciseList();
            $data = $model->getWriteList($cate_id_arr,1);
            // 删除剑雅5、剑雅6、剑雅7
//            unset($data[0][0][0]);
//            unset($data[0][0][1]);
//            unset($data[0][0][2]);
            $cate_list = $data[1][0][$cate_id];

            $list = [];
            if ($cate_list) {
                // 拆分 剑雅-Test-Task
                foreach ($cate_list as $key => $value) {
                    $value['name'] = str_replace(' ','',$value['name']);
                    // $tmp = explode('-', $value['name']);
                    // $cate_list[$key]['test_name'] = trim($tmp[1]);
                    // $cate_list[$key]['task_name'] = trim($tmp[2]);
                    $cate_list[$key]['test_name'] = substr(trim($value['name']),0, -6);
                    $cate_list[$key]['task_name'] = substr(trim($value['name']), -5);

                }

                $list = $cate_list;
            }

            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }

            $datelist = $data[0];
        } elseif ($category == 'type') { // 按题型练习
            // 分类
            // 默认分类id
            $cate_id_arr = array(512, 513, 514);
            // 没有就默认cate_id=414
            $cate_id = intval(Yii::$app->request->get('cate_id', 515));
            $model = new ExerciseList();
            $data = $model->getWriteList($cate_id_arr);

            $cate_id = Yii::$app->request->get('cate_id',620);//线上620.本地618
            $cate_model = new ExerciseCategory();
            $cate_list = $cate_model->getWriteExerciseByType($cate_id);

            $list = [];
            if ($cate_list) {
                // 拆分 剑雅-Test-Task
                foreach ($cate_list as $key => $value) {
                    $value['name'] = str_replace(' ','',$value['name']);
                    // $tmp = explode('-', $value['name']);
                    // $cate_list[$key]['test_name'] = trim($tmp[1]);
                    // $cate_list[$key]['task_name'] = trim($tmp[2]);
                    $cate_list[$key]['test_name'] = substr(trim($value['name']),0, -6);
                    $cate_list[$key]['task_name'] = substr(trim($value['name']), -5);
                    $list = $cate_list;
                }
            }
            $res = [];
            foreach ($list as $key => $value) {
                if (array_key_exists($value['test_name'], $res)) {
                    $res[$value['test_name']][] = $value;
                } else {
                    $res[$value['test_name']][] = $list[$key];
                }
            }

            $datelist = $data[0];
            // // 添加sessionid 状态值  和统计完成数量
            // foreach($list[1] as$ky=> $v){
            //     // $model->getlistennumber($v['id'],3);
            //     $num = $model->getlistennumberspeak($v['id'],3);
            //     // var_dump($num);
            //     $list[1][$ky]['num']=$num;
            // }
        }
        // 右边banner
        $banner = ExerciseBanner::find()->where(['typeid'=>3])->asArray()->one();

        $this->title = '雅思雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _雅思雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '雅思雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';

        return $this->render('new_index', [
            'type' =>3,
            'typename' =>'写作练习',
            'banner' => $banner,
            'datelist' => $datelist,
            'list' => $res,
            'cate_id' => $cate_id,
            'category' => $category
        ]);
    }

    /**
     * @Title  [听力详情]
     * @Author Don
     * @Date   2021-04-20
     * @return [type]
     */
    public function actionListenDetail()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';
        return $this->render('listen_detail',[
            'content_id' => $content_id,
            'tmp_name' => 'listen',
        ]);
    }

    public function actionListenReview()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        $this->title = '申友雅思（IELTS） _在线备考平台__实用做题平台 _雅思培训 _雅思英语学习_雅思培训那家好 _申友雅思官网';
        $this->keywords = 'IELTS考试,雅思考试时间,雅思英语,雅思学习,雅思报名官网,雅思培训班,雅思课程,雅思培训机构';
        $this->description = '申友雅思官网专门为雅思考生打造的在线练习平台，针对提分学员、传授雅思培训高分秘诀，IELTS 课程包括雅思方法课、 互动陪练、在线智能练习、智能测评反馈等雅思教学模块为一体的 IELTS 备考方案，通过网站和APP给用户提供高效、便捷的立体学习系统';
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where("content_id=$content_id")->orderBy('content_id asc')->one();

        return $this->render('listen_review',[
            'content_id' => $content_id,
            'tmp_name' => 'listen',
            'cate_id' => $name['cate_id'],
        ]);
    }

    /**
     * @Title  [精听]
     * @Author Don
     * @Date   2023-10
     * @return [type]
     */
    public function actionListeningIntensive()
    {
        $id = Yii::$app->request->get('id');
        $userId = Yii::$app->session->get('userId');
//        if ($userId == false) {
//            die(json_encode(['message' => '未登录', 'code' => 5]));
//        }
        $data = ExerciseListDetail::find()->asArray()->select(['sencenter', 'problemComplement', 'duration'])->where('pid=' . $id)->orderBy('id asc')->one();
        $listen = ExerciseList::find()->asArray()->select(['listeningFile'])->where('content_id=' . $id)->orderBy('id asc')->one();
        $listen = ELD::getlabeldeletesetences($listen['listeningFile']);
        $listen = count($listen) > 1 ? $listen[1] : $listen[0];
        $data['problemComplement'] = ELD::getlabeldeletesetences($data['problemComplement']);
        $data['sencenter'] = ELD::getlabeldeletesetences($data['sencenter']);
        $time = explode(',', nl2br($data['duration']));
        static $detail = array();
        foreach ($data['problemComplement'] as $k => $v) {
            $detail[$k]['en'] = html_entity_decode($v, ENT_QUOTES);
            $detail[$k]['cn'] = trim(trim(str_replace([PHP_EOL, '\r'], '', $data['sencenter'][$k]), PHP_EOL), '\r');
            $detail[$k]['start_time'] = isset($time[2 * $k]) ? $time[2 * $k] : '';
            $detail[$k]['end_time'] = isset($time[$k * 2 + 1]) ? $time[$k * 2 + 1] : '';
        }
        $data['code'] = 1;
        return $this->render('listen_intensive',['detail' => $detail, 'count' => count($detail), 'listen' => $listen != false ? 'https://www.thinkuprep.com' . $listen : '']);
    }

    /**
     * @Title  [口语详情]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionSpeakDetail()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }

        $detail = ExerciseListDetail::find()->where(['pid'=>$content_id])->asArray()->one();

        return $this->render('speak_detail', [
            'pid' => $content_id,
            'content_id' => $detail['content_id'],
            'tmp_name' => 'speak',
        ]);
    }

    public function actionSpeakReview()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where("content_id=$content_id")->orderBy('content_id asc')->one();
//        $userId=765;
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        $detail = ExerciseListDetail::find()->where(['pid'=>$content_id])->asArray()->one();
        return $this->render('speak_review', [
            'pid' => $content_id,
            'content_id' => $detail['content_id'],
            'cate_id' => $name['cate_id'],
            'tmp_name' => 'speak',
        ]);
    }

    /**
     * @Title  [阅读详情]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionReadDetail()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        return $this->render('read_detail',[
            'content_id' => $content_id,
            'tmp_name' => 'read',
        ]);
    }

    public function actionReadReview()
    {
        $content_id = Yii::$app->request->get('content_id');
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where("content_id=$content_id")->orderBy('content_id asc')->one();
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        return $this->render('read_review',[
            'content_id' => $content_id,
            'tmp_name' => 'read',
            'cate_id' => $name['cate_id'],
        ]);
    }

    /**
     * @Title  [写作详情]
     * @Author Don
     * @Date   2021-04-28
     * @return [type]
     */
    public function actionWriteDetail()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        return $this->render('write_detail', [
            'content_id' => $content_id,
            'tmp_name' => 'write',
        ]);
    }

    public function actionWriteReview()
    {
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if(!$userId){
            $url ="/login.html?source=10&url=http://".$_SERVER['SERVER_NAME'].Yii::$app->request->getUrl();
            return $this->redirect($url);
        }
        return $this->render('write_review', [
            'content_id' => $content_id,
            'tmp_name' => 'write',
        ]);
    }

    /**
     * @Title  [听力结果]
     * @Author Don
     * @Date   2021-04-20
     * @return [type]
     */
    public function actionListenResult()
    {
        $resultid = Yii::$app->request->get('resultid');
        $content_id = Yii::$app->request->get('content_id');

        return $this->render('listen_result',[
            'resultid' => $resultid,
            'content_id' => $content_id
        ]);
    }

    /**
     * @Title  [口语结果]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionSpeakResult()
    {
        $content_id = Yii::$app->request->get('content_id');

        return $this->render('speak_result',[
            'content_id' => $content_id
        ]);
    }

    /**
     * @Title  [阅读结果]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionReadResult()
    {
        $resultid = Yii::$app->request->get('resultid');
        $content_id = Yii::$app->request->get('content_id');
        return $this->render('read_result',[
            'resultid' => $resultid,
            'content_id' => $content_id
        ]);
    }

    /**
     * @Title  [写作结果页]
     * @Author Don
     * @Date   2021-04-28
     * @return [type]
     */
    public function actionWriteResult()
    {
        $content_id = Yii::$app->request->get('content_id');

        return $this->render('write_result', [
            'content_id' => $content_id
        ]);
    }

    /**
     * @Title  [写作结果]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionGetWriteResult()
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $id = Yii::$app->request->get('content_id');
        // $type = Yii::$app->request->get('type',1);//开始1 重新2

        $son = ExerciseListDetail::find()->where(['pid'=>$id])->asArray()->all();
        // 查询父类
        $parent = ExerciseList::find()->where(['content_id'=>$id])->asArray()->one();
        $list = [];
        foreach ($son as $k => $v) {
            // if ($type == 2) {
            //     $son[$k]['userAnswer'] = '';
            //     // $son[$k]['answerliked'] = 0;
            //     // $son[$k]['answerId'] = '';
            //     // $son[$k]['time'] = 0;
            // }else{
                $answerTem = TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['content_id'].' and userid='.$userId .' and answer !=""')->one();
                $son[$k]['userAnswer'] = $answerTem != false ? nl2br($answerTem['answer']) : '';
                $son[$k]['time'] = $answerTem != false ? $answerTem['time'] : 0;
                if ($answerTem != false) {
                    $remark = ExerciseCorrection::find()->asArray()->where('result_id=' . $answerTem['id'])->one();
                }
                $son[$k]['answerRemark'] = isset($remark) && $remark != false ? json_decode($remark['result'],true) : '';
            // }
            // $tem = TestResult::find()->asArray()->select(['x2_user.userName','x2_user.image','x2_ielts_test_result.*'])->where('pid='.$id.' and testid='.$v['content_id']." and answer !=''")->leftJoin("x2_user",'x2_user.id=x2_ielts_test_result.userId')->orderBy('like desc')->limit(10)->all();
            // $list[$k] = $tem != false ? $tem : array();

        }

        die(json_encode(['message' => 'success', 'code' => 1,'parent'=>$parent, 'son'=>$son]));
    }

    /**
     * @Title  [听力做题的题目]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionListenExercise()
    {
        $model = new ExerciseList();
        $id = Yii::$app->request->get('content_id');
        $type = Yii::$app->request->get('type',1);//开始做题重新做题1,2继续和结果做题
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where("content_id=$id")->orderBy('content_id asc')->one();
        $pids=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where('cate_id='.$name['cate_id'].' and name="'.$name['name'].'"')->orderBy('content_id asc')->all();
        if($pids==false){
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $pids= array_column($pids,'content_id');
        $data['article'] = ExerciseList::find()->where(['pid'=>0, 'content_id'=>$pids[0]])->asArray()->one();
        if ($type == 1) {
            $data['resultid']=time();
            $data['newid']=time();
        } else {
            $pidsStr=implode(',',$pids);
            $data['resultid'] = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $name['cate_id'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['resultid'];
            $data['newid'] = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $name['cate_id'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['newid'];
        }

        foreach($pids as $k =>$v){
            if($v!=false){
                $parent = ExerciseList::find()->where(['content_id'=>$v])->asArray()->one();
                $son = ExerciseListDetail::find()->where(['pid'=>$v])->asArray()->all();
                if ($parent['type'] == 3) {
                    if ($parent['questionType'] == 2) {
                        $parent['answerCount'] = count($son);
                    } else {
                        $parent['answerCount'] = !empty($son[0]['alternatives'])?strlen($son[0]['alternatives']):strlen($son[0]['answer']);
                    }
                }

                $data['topic'][$k]['parent'] = $parent;
                $data['topic'][$k]['son'] = $son;
                foreach($data['topic'][$k]['son'] as $key=>$val){
                    if($v!=false) {
                        $tem = Yii::$app->db->createCommand("select pid,result,answer,really from {{%ielts_test_result}} where fid=" . $data['topic'][$k]['parent']['cate_id'] . " and testid=".$data['topic'][$k]['son'][$key]['content_id']."  and userid=$userId and answer!='' and newid=".$data['newid']." order by id desc")->queryOne();
                    }
                    if(!isset($tem)||$tem==false){
                        $data['topic'][$k]['son'][$key]['userAnswer']='';
                    }else{
                        $data['topic'][$k]['son'][$key]['userAnswer'] = $tem['answer'];
                    }
                }

                // 2021-11-30 添加浏览量计数
                ExerciseList::updateAll(['viewCount'=>$parent['viewCount']+1], 'id='.$parent['id']);
            }
        }
        // 题目序号
        $question_list = ExerciseListDetail::find()->where(['in', 'pid', $pids])->asArray()->all();

        foreach ($question_list as $key => $value) {
            // 题目序号标记
            $exercise_status = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$value['pid'], 'content_id'=>$value['content_id']])->asArray()->one();
            $question_list[$key]['status'] = !empty($exercise_status) ? 1 : 0;

            // 判断是否已经做题
            $tmp = TestResult::find()->asArray()->where('pid='.$value['pid'].' and testid='.$value['content_id'].' and userid='.$userId )->one();
            $question_list[$key]['isDo'] = $tmp ? 1 : 0;
        }

        $data['topic'] = $model->listenFormat($data['topic']);
        $data['question_list'] = $question_list;
        $data['code'] = 1;

        die(json_encode($data));
    }

    /**
     * @Title  [获取听力下面的题号以及做题状态]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionReviewListen()
    {
        $userId = Yii::$app->session->get('userId');
        $pid = Yii::$app->request->get('pid');
        $content_id = Yii::$app->request->get('content_id');
        $tmp = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$pid, 'content_id'=>$content_id])->asArray()->one();
        if (empty($tmp)) {
            $model = new ExerciseStatus();
            $model->pid = $pid;
            $model->content_id = $content_id;
            $model->userId = $userId;
            if ($model->save()) {
                $res['code'] = 1;
                $res['message'] = 'success';
            } else {
                $res['code'] = 0;
                $res['message'] = 'fail';
            }
        } else {
            $res['code'] = 1;
            $res['message'] = 'success';
        }
        die(json_encode($res));
    }

    /**
     * @Title  [获取听力结果]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionGetListenResult()
    {
        $resultid = Yii::$app->request->get('resultid');
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if (!$userId) {
            die(json_encode(['message' => '未登录', 'code' => 4]));
        }
        $userInfo = User::find()->where(['id' =>$userId])->asArray()->One();
        $res = ExerciseResult::find()->where(['userid'=>$userId, 'resultid'=>$resultid, 'typeid'=>1])->asArray()->all();

        if (!$res) {
            die(json_encode(['message' => 'fail', 'code' => 5]));
        }
        // 显示题号
        foreach ($res as $k => $v) {
            $number = ExerciseListDetail::find()->where(['content_id'=>$v['testid']])->asArray()->one();
            $res[$k]['questionNumber'] = $number['name'];
        }

        $data = [];
        $data['userInfo'] = $userInfo;
        // $pid = $res[0]['pid'];
        $list = ExerciseList::find()->where(['content_id'=>$content_id])->asArray()->one();
        // test名称
        $data['test_name'] = $list['name'];
        // test时间
        $data['test_time'] = date('Y-m-d',$res[0]['createtime']);
        // 总题数
        $data['total'] = count($res);
        // 正确题数
        $data['right'] = 0;
        // 用时
        $data['time'] = 0;
        foreach ($res as $key => $value) {
            if ($value['result'] == 1) {
                $data['right'] ++;
            }
            $data['time'] = $value['time'];
        }
        // 正确率
        $rate = (sprintf("%.2f", $data['right']/$data['total'])) * 100;
        // 得分
        $data['score'] = RankingAll::score($rate);

        $data['list'] = $res;

        die(json_encode($data));
    }

    /**
     * @Title  [口语做题的题目]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionSpokenExercise()
    {
        $id = Yii::$app->request->get('content_id');
        $type = Yii::$app->request->get('type',1);//开始1 重新2
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $son = ExerciseListDetail::find()->where(['pid'=>$id])->asArray()->all();
        // 查询父类
        $parent = ExerciseList::find()->where(['content_id'=>$id])->asArray()->one();
        $resultId= Yii::$app->db->createCommand("select resultid,newid from {{%ielts_test_result}} where fid=" . $parent['cate_id'] . " and pid =" . $id. " and userid=$userId order by id desc")->queryOne();
        if ($resultId==false) {
            $resultid =  time();
            $newid =  time();
        } else {
            $resultid = $resultId['resultid'];
            $newidTem = $resultId['newid'];
            $newid = ($newidTem == false ? time() : $newidTem);
        }
        // 2021-11-30 添加浏览量计数
        ExerciseList::updateAll(['viewCount'=>$parent['viewCount']+1], 'id='.$parent['id']);
        $list = [];
        foreach ($son as $k => $v) {
            if ($type == 2) {
                $son[$k]['userAnswer'] = '';
                $son[$k]['answerliked'] = 0;
                $son[$k]['answerId'] = '';
                $son[$k]['time'] = 0;
            }else{
                $answerTem = TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['content_id'].' and userid='.$userId .' and answer !=""')->orderBy('id desc')->one();
                $son[$k]['userAnswer'] = $answerTem != false ? $answerTem['answer'] : '';
                $son[$k]['answerliked'] = $answerTem != false ? $answerTem['like'] : 0;
                $son[$k]['answerId'] = $answerTem != false ? $answerTem['id'] : '';
                $son[$k]['time'] = $answerTem != false ? $answerTem['time'] : 0;
                if ($answerTem != false) {
                    $remark = ExerciseCorrection::find()->asArray()->where('result_id=' . $answerTem['id'])->one();
                }
                $son[$k]['answerRemark'] = isset($remark) && $remark != false ? $remark['result'] : '';
                $son[$k]['suggest'] = $son[$k]['answerRemark'] != false ? ExerciseCorrection::getSpokenSuggest($son[$k]['answerRemark']) : '';
            }
            $tmp = ExerciseResult::find()->asArray()->where("testid={$v['content_id']} and userid=$userId and typeid=4")->orderBy('id desc')->one();  //typeid 听阅写口
            if (!empty(@$tmp['answer'])){
                $son[$k]['my_answer'] = $tmp['answer'];
                $son[$k]['judge'] = $tmp['result'];
            }else{
                $son[$k]['my_answer'] = '';
                $son[$k]['judge'] = '';
            }

            $tem = TestResult::find()->asArray()->select(['x2_user.userName','x2_user.image','x2_ielts_test_result.*'])->where('pid='.$id.' and testid='.$v['content_id']." and answer !=''")->leftJoin("x2_user",'x2_user.id=x2_ielts_test_result.userId')->orderBy('like desc')->limit(10)->all();
            $list[$k] = $tem != false ? $tem : array();

        }
        // 题目序号
        $model = new ExerciseList();
        $question_list = $model->getSpeakList($parent['cate_id']);

        foreach ($question_list as $key => $value) {
            $res = ExerciseListDetail::find()->where(['pid'=>$value['content_id']])->asArray()->one();
            // 题目序号标记
            $exercise_status = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$value['content_id'], 'content_id'=>$res['content_id']])->asArray()->one();
            $question_list[$key]['status'] = !empty($exercise_status) ? 1 : 0;

            // 判断是否已经做题
            $tmp = TestResult::find()->asArray()->where('pid='.$id.' and testid='.$res['content_id'].' and userid='.$userId )->one();
            $question_list[$key]['isDo'] = $tmp ? 1 : 0;
        }

        die(json_encode(['question_list'=>$question_list, 'parent' => $parent, 'son' => $son, 'list' => $list, 'code' => 1, 'resultid' => $resultid, 'newid' => $newid]));
    }

    /**
     * @Title  [获取口语下面的题号以及做题状态]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionReviewSpeak()
    {
        $userId = Yii::$app->session->get('userId');
        $pid = Yii::$app->request->get('pid');
        $id = Yii::$app->request->get('content_id');
        $type = Yii::$app->request->get('type', 1); // 1存 2删
        // $data = ExerciseListDetail::find()->where(['pid'=>$id])->asArray()->one();
        // $tmp = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$id, 'content_id'=>$data['content_id']])->asArray()->one();
        // if (empty($tmp)) {
        //     $model = new ExerciseStatus();
        //     $model->pid = $id;
        //     $model->content_id = $data['content_id'];
        //     $model->userId = $userId;
        //     if ($model->save()) {
        //         $res['code'] = 1;
        //         $res['message'] = 'success';
        //     } else {
        //         $res['code'] = 0;
        //         $res['message'] = 'fail';
        //     }
        // } else {
        //     $res['code'] = 1;
        //     $res['message'] = 'success';
        // }
        if (!$pid || !$id) {
            $res['code'] = 1;
            $res['message'] = 'success';
        } else {
            if ($type == 1) {
                $tmp = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$pid, 'content_id'=>$id])->asArray()->one();
                if (!$tmp) {
                    $model = new ExerciseStatus();
                    $model->pid = $pid;
                    $model->content_id = $id;
                    $model->userId = $userId;
                    if ($model->save()) {
                        $res['code'] = 1;
                        $res['message'] = 'success';
                    } else {
                        $res['code'] = 0;
                        $res['message'] = 'fail';
                    }
                }
            } elseif ($type == 2) {
                $tmp = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$pid, 'content_id'=>$id])->asArray()->one();
                ExerciseStatus::deleteAll("id=:id", array(':id' => $tmp['id']));
                $res['code'] = 1;
                $res['message'] = 'success';
            }
        }
        die(json_encode($res));
    }

    /**
     * @Title  [上传口语音频]
     * @Author Don
     * @Date   2021-05-05
     * @return [type]
     */
    public function actionUploadSpeakAudio()
    {
        $token = Yii::$app->request->post('token');
        $authenticity_token = '12345';
        if ($token == $authenticity_token) {
            $file = $_FILES['upload_file'];
            $upload = new UploadFile();
            $upload->int_max_size = 20145728;
            $upload->arr_allow_exts = array('mp3', 'ogg', 'wav');
            $upload->str_save_path = Yii::$app->params['upSpoken'];
            //Aaron ： 处理html5上传情况
            if (Yii::$app->request->post('client') == 'html5') {
                $file['name'] = Yii::$app->request->post('filename');
            }
            $arr_rs = $upload->upload($file);
            if ($arr_rs['int_code'] == 1) {
                $filePath = '/' . Yii::$app->params['upSpoken'] . $arr_rs['arr_data']['arr_data'][0]['savename'];
                $res['code'] = 1;
                $res['file'] = $filePath;
                $res['message'] = '上传成功';
            } else {
                $res['code'] = 0;
                $res['message'] = '上传失败，请重试';
            }
        } else {
            $res['code'] = 0;
            $res['message'] = '上传失败，令牌错误';
        }
        die(json_encode($res));
    }

    /**
     * @Title  [阅读做题的题目]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionReadExercise()
    {
        $model = new ExerciseList();
        $id = Yii::$app->request->get('content_id');
        $type = Yii::$app->request->get('type',1);//开始做题重新做题1,2继续和结果做题
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where("content_id=$id")->orderBy('content_id asc')->one();
        $pids=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id'])->where('cate_id='.$name['cate_id'].' and name="'.$name['name'].'"')->orderBy('content_id asc')->all();
        if($pids==false){
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $pids= array_column($pids,'content_id');
        $data['article'] = ExerciseList::find()->where(['pid'=>0, 'content_id'=>$pids[0]])->asArray()->one();
//        $data['article']['description'] = str_replace("\r",'<br>',$data['article']['description']);
//        //$data['article']['description'] = str_replace('<br>','<br><br>',$data['article']['description']);
//        $data['article']['description'] = str_replace('</p>','</p><br>',$data['article']['description']);
        $data['article']['description'] = ExerciseList::articleformat($data['article']['description']);
        if ($type == 1) {
            $data['resultid']=time();
            $data['newid']=time();
        } else {
            $pidsStr=implode(',',$pids);
            $data['resultid'] = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $name['cate_id'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['resultid'];
            $data['newid'] = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $name['cate_id'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['newid'];
        }

        foreach($pids as $k =>$v){
            if($v!=false){
                // 阅读多选题判断答案个数
                $parent = ExerciseList::find()->where(['content_id'=>$v])->asArray()->one();
                $son = ExerciseListDetail::find()->where(['pid'=>$v])->asArray()->all();
                if ($parent['numbering'] == 1) {
                    if ($parent['questionType'] == 2) {
                        $parent['answerCount'] = count($son);
                    } else {
                        $parent['answerCount'] = strlen($son[0]['answer']);
                    }
                }
                
                $data['topic'][$k]['parent'] = $parent;
                $data['topic'][$k]['son'] = $son;

                foreach($data['topic'][$k]['son'] as $key=>$val){
                    if($v!=false) {
                        $tem = Yii::$app->db->createCommand("select pid,result,answer,really from {{%ielts_test_result}} where fid=" . $data['topic'][$k]['parent']['cate_id'] . " and testid=".$data['topic'][$k]['son'][$key]['content_id']."  and userid=$userId and answer!='' and newid=".$data['newid']." order by id desc")->queryOne();

                    }
                    $tmp = ExerciseResult::find()->asArray()->where("testid={$val['content_id']} and userid=$userId and typeid=2")->orderBy('id desc')->one();  //typeid 听阅写口
                    if (!empty(@$tmp['answer'])){
                        $data['topic'][$k]['son'][$key]['my_answer'] = $tmp['answer'];
                        $data['topic'][$k]['son'][$key]['judge'] = $tmp['result'];
                    }else{
                        $data['topic'][$k]['son'][$key]['my_answer'] = '';
                        $data['topic'][$k]['son'][$key]['judge'] = '';
                    }
                    if(!isset($tem)||$tem==false){
                        $data['topic'][$k]['son'][$key]['userAnswer']='';
                    }else{
                        $data['topic'][$k]['son'][$key]['userAnswer'] = $tem['answer'];
                    }
                }
                // 2021-11-30 添加浏览量计数
                ExerciseList::updateAll(['viewCount'=>$parent['viewCount']+1], 'id='.$parent['id']);
            }
        }

        // 题目序号
        $question_list = ExerciseListDetail::find()->where(['in', 'pid', $pids])->asArray()->all();

        foreach ($question_list as $key => $value) {
            // 题目序号标记
            $exercise_status = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$value['pid'], 'content_id'=>$value['content_id']])->asArray()->one();
            $question_list[$key]['status'] = !empty($exercise_status) ? 1 : 0;

            // 判断是否已经做题
            $tmp = TestResult::find()->asArray()->where('pid='.$value['pid'].' and testid='.$value['content_id'].' and userid='.$userId )->one();
            $question_list[$key]['isDo'] = $tmp ? 1 : 0;
        }


        $data['topic'] = $model->readformat($data['topic']);

        // $data['isCollect'] = QuestionCollect::isCollect(implode(',', $pids), 1);
        // $data['mark'] = QuestionMark::getMark(implode(',', $pids), 1);
        $data['question_list'] = $question_list;
        $data['code'] = 1;

        die(json_encode($data));
    }

    /**
     * @Title  [保存听力阅读做题数据]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionSaveListenReadAnswer()
    {
        // f_d($_POST);
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $typeid = Yii::$app->request->post('typeid',2);
        $resultid = Yii::$app->request->post('resultid');
        $newid = Yii::$app->request->post('newid');
        $fid = Yii::$app->request->post('cate_id');
        $result = Yii::$app->request->post('answer');
        if (!$result) {
            die(json_encode(['message' => '未收到答案', 'code' => 4]));
        }
        $time = Yii::$app->request->post('time');
        // $result = json_decode($result, true);
        foreach ($result as $key => $value) {
            // 查父级content_id
            $tmp = ExerciseListDetail::find()->where(['content_id'=>$value['content_id']])->asArray()->one();
            $model = new ExerciseResult();
            $model->testid = $testid = $value['content_id'];//小题的id
            $model->fid = $fid;//分类的id
            $model->pid = $tmp['pid'];//pid
            $model->resultid = $resultid;//同一次做题的id
            $model->newid = $newid;//同一次做题的id
            $model->answer = $answer = rtrim(ltrim($value['answer']));//用户答案
            $model->really = $really = $value['trueAnswer'];//正确答案
            $model->result = $result = 0;
            $model->userid = $userId;
            $model->typeid = $typeid;
            $model->time = $time;
            $model->createtime = time();
            $answer = strtolower(ExerciseResult::romanNumber($answer));
            $really = strtolower(ExerciseResult::romanNumber(trim($really)));
            if ($answer == $really) {
                $model->result = $result = 1;
            } else {
                $answerData = explode('|', $really);
                $answerData = $this->trim_array_element($answerData);
                if (in_array($answer, $answerData)) {
                    $model->result = $result =  1;
                }
            }
            $sign = ExerciseResult::find()->asArray()->where("testid=$testid and userid=$userId AND resultid=$resultid and newid=$newid")->one();
            if ($sign) {
                if($sign['answer'] == $model->answer){
                    // die(json_encode(['message' => '保存成功', 'code' => 1]));
                    continue;
                }
                $re = $model->updateAll(['answer' => $model->answer], "userid=$userId and resultid=$resultid and testid=$testid and newid=$newid");
            } else {
                $re = $model->save();
            }
            if (!$re) {
                die(json_encode(['message' => '保存失败', 'code' => 0]));
            }
        }

        $contentModel = new ExerciseList();
        $contentModel->getlistentestorder($typeid);


        die(json_encode(['message' => '保存成功', 'code' => 1, 'resultid'=>$resultid]));
    }

    /**
     * @Title  [获取阅读结果]
     * @Author Don
     * @Date   2021-05-07
     * @return [type]
     */
    public function actionGetReadResult()
    {
        $resultid = Yii::$app->request->get('resultid');
        $content_id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if (!$userId) {
            die(json_encode(['message' => '未登录', 'code' => 4]));
        }
        $userInfo = User::find()->where(['id' =>$userId])->asArray()->One();
        $res = ExerciseResult::find()->where(['userid'=>$userId, 'resultid'=>$resultid, 'typeid'=>2])->asArray()->all();
        
        if (!$res) {
            die(json_encode(['message' => 'fail', 'code' => 5]));
        }
        // 显示题号
        foreach ($res as $k => $v) {
            $number = ExerciseListDetail::find()->where(['content_id'=>$v['testid']])->asArray()->one();
            $res[$k]['questionNumber'] = $number['name'];
        }

        $data = [];
        $data['userInfo'] = $userInfo;
        // $pid = $res[0]['pid'];
        $list = ExerciseList::find()->where(['content_id'=>$content_id])->asArray()->one();
        // test名称
        $data['test_name'] = $list['name'];
        // test时间
        $data['test_time'] = date('Y-m-d',$res[0]['createtime']);
        // 总题数
        $data['total'] = count($res);
        // 正确题数
        $data['right'] = 0;
        // 用时
        $data['time'] = 0;
        foreach ($res as $key => $value) {
            if ($value['result'] == 1) {
                $data['right'] ++;
            }
            $data['time'] = $value['time'];
            $tmp = ExerciseList::find()->where(['content_id'=>$value['pid']])->asArray()->one();
            if ($tmp['numbering'] == 3) {  // 是非题
                // 判断是yes no 还是 true false 
                $descriptionStr = ExerciseListDetail::find()->where(['content_id'=>$value['testid']])->asArray()->one();
                if (strpos($descriptionStr['description'], 'YES') !== false) {
                    $res[$key]['answer'] = $value['answer'] == 'A' ? 'YES' : ($value['answer'] == 'B' ? 'NO' : 'NOT GIVEN');
                    $res[$key]['really'] = $value['really'] == 'A' ? 'YES' : ($value['really'] == 'B' ? 'NO' : 'NOT GIVEN');
                } else {
                    $res[$key]['answer'] = $value['answer'] == 'A' ? 'TRUE' : ($value['answer'] == 'B' ? 'FALSE' : 'NOT GIVEN');
                    $res[$key]['really'] = $value['really'] == 'A' ? 'TRUE' : ($value['really'] == 'B' ? 'FALSE' : 'NOT GIVEN');
                }
            }
        }
        // 正确率
        $rate = (sprintf("%.2f", $data['right']/$data['total'])) * 100;
        // 得分
        $data['score'] = RankingAll::formatScore(RankingAll::score($rate));

        $data['list'] = $res;

        die(json_encode($data));
    }
    

    /**
     * @Title  [写作做题]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionWriteExercise()
    {
        $id = Yii::$app->request->get('content_id');
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }

        $son = ExerciseListDetail::find()->where(['pid'=>$id])->asArray()->all();
        // 查询父类
        $parent = ExerciseList::find()->where(['content_id'=>$id])->asArray()->one();
        // 2021-11-30 添加浏览量计数
        ExerciseList::updateAll(['viewCount'=>$parent['viewCount']+1], 'id='.$parent['id']);
        $resultId= Yii::$app->db->createCommand("select resultid,newid from {{%ielts_test_result}} where fid=" . $parent['cate_id'] . " and pid =" . $id. " and userid=$userId order by id desc")->queryOne();
        if ($resultId==false) {
            $resultid =  time();
            $newid =  time();
        } else {
            $resultid = $resultId['resultid'];
            $newidTem = $resultId['newid'];
            $newid=($newidTem==false?time():$newidTem);
        }
        foreach($son as $k=>$v){
            $tem=TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['content_id'] ." and userid=$userId and answer !=''")->orderBy('id desc')->one();
            $son[$k]['userAnswer']=$tem!=false?$tem['answer']:'';
            $son[$k]['my_answer']=$tem!=false?$tem['answer']:0;
        }

        die(json_encode(['parent' => $parent, 'son' => $son[0], 'code' => 1, 'resultid' => $resultid, 'newid' => $newid]));
    }

    /**
     * @Title  [保存口语或者写作答案]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionSaveSpokenWriteAnswer()
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $model = new ExerciseResult();
        $model->testid = $testid = Yii::$app->request->post('testid');//小题的id
        $model->fid = $fid = Yii::$app->request->post('fid');//分类的id
        $model->pid = $pid = Yii::$app->request->post('pid');//pid
        $model->resultid = $resultid = Yii::$app->request->post('resultid');//同一次做题的id
        $model->newid = $newid = Yii::$app->request->post('newid');//同一次做题的id
        $model->answer = $answer = Yii::$app->request->post('answer');//用户答案
        $model->really = $really = '';//正确答案
        $model->result = $result = 1;//默认正确还是错误
        $model->userid = $userId;
        $model->typeid = Yii::$app->request->post('typeid',4);
        $model->time = Yii::$app->request->post('time');
        $model->createtime = time();

        $sign = ExerciseResult::find()->asArray()->where("testid=$testid and userId=$userId AND resultid=$resultid and newid=$newid")->one();
        if ($sign) {
            $data=['answer' => $model->answer];
            if($model->time!=$sign['time']) $data=['answer' => $model->answer,'time'=>$model->time];
            $re = $model->updateAll($data, "userid=$userId and $resultid=$resultid and testid=$testid and newid=$newid");
            $result_id = $sign['id'];
        } else {
            $re = $model->save();
            $result_id = $model->id;
        }
        if ($result_id) {
            if ($model->typeid == 3) {
                $remark = Write::writeCorrect($answer, 1, 'ielts');
                $result = json_decode($remark, true);
//                $result = json_decode(file_get_contents('https://www.thinkuprep.com/cn/api/write'), true);//有结果只保存结果
                $res = $result['errorCode'] == 0 ? json_encode($result['Result']) : '';
            } else {
                $res = Yii::$app->request->post('remark');
//                $res = file_get_contents('https://www.thinkuprep.com/cn/api/spoken?file=' . $model->answer . '&text=speak');//有结果只保存结果
            }
            $correct = ExerciseCorrection::find()->where("result_id=$result_id")->asArray()->one();
            if ($correct) {
                ExerciseCorrection::updateAll(['result' => $res], 'result_id=' . $result_id);
            } else {
                $correctModel = new ExerciseCorrection();
                $correctModel->result_id = $result_id;
                $correctModel->result = $res;
                $correctModel->save();
            }
        }
        $contentModel = new ExerciseList();
        $contentModel->getlistentestorder($model->typeid);
        if($re){
            die(json_encode(['message' => '保存成功', 'code' => 1, 'id'=>$result_id]));
        }
        die(json_encode(['message' => '保存失败', 'code' => 1]));
    }

    /**
     * @Title  [获取答案]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public function actionGetSpeakResult()
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $id = Yii::$app->request->get('content_id');
        // $type = Yii::$app->request->get('type',1);//开始1 重新2

        $son = ExerciseListDetail::find()->where(['pid'=>$id])->asArray()->all();
        // 查询父类
        $parent = ExerciseList::find()->where(['content_id'=>$id])->asArray()->one();
        $list = [];
        foreach ($son as $k => $v) {
            // if ($type == 2) {
            //     $son[$k]['userAnswer'] = '';
            //     // $son[$k]['answerliked'] = 0;
            //     // $son[$k]['answerId'] = '';
            //     // $son[$k]['time'] = 0;
            // }else{
                $answerTem = TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['content_id'].' and userid='.$userId .' and answer !=""')->one();
                $son[$k]['userAnswer'] = $answerTem != false ? $answerTem['answer'] : '';
                $son[$k]['time'] = $answerTem != false ? $answerTem['time'] : 0;
                if ($answerTem != false) {
                    $remark = ExerciseCorrection::find()->asArray()->where('result_id=' . $answerTem['id'])->one();
                }
                $son[$k]['answerRemark'] = isset($remark) && $remark != false ? $remark['result'] : '';
                $son[$k]['suggest'] = $son[$k]['answerRemark'] != false ? ExerciseCorrection::getSpokenSuggest($son[$k]['answerRemark']) : '';
                // $son[$k]['answerliked'] = $answerTem != false ? $answerTem['like'] : 0;
                // $son[$k]['answerId'] = $answerTem != false ? $answerTem['id'] : '';
                // $son[$k]['time'] = $answerTem != false ? $answerTem['time'] : 0;
            // }
            // $tem = TestResult::find()->asArray()->select(['x2_user.userName','x2_user.image','x2_ielts_test_result.*'])->where('pid='.$id.' and testid='.$v['content_id']." and answer !=''")->leftJoin("x2_user",'x2_user.id=x2_ielts_test_result.userId')->orderBy('like desc')->limit(10)->all();
            // $list[$k] = $tem != false ? $tem : array();

        }
        // 题目序号
        $model = new ExerciseList();
        $question_list = $model->getSpeakList($parent['cate_id']);

        foreach ($question_list as $key => $value) {
            $res = ExerciseListDetail::find()->where(['pid'=>$value['content_id']])->asArray()->one();
            // 题目序号标记
            $exercise_status = ExerciseStatus::find()->where(['userId'=>$userId, 'pid'=>$value['content_id'], 'content_id'=>$res['content_id']])->asArray()->one();
            $question_list[$key]['status'] = !empty($exercise_status) ? 1 : 0;

            // 判断是否已经做题
            $tmp = TestResult::find()->asArray()->where('pid='.$id.' and testid='.$res['content_id'].' and userid='.$userId )->one();
            $question_list[$key]['isDo'] = $tmp ? 1 : 0;
        }

        die(json_encode(['message' => 'success', 'code' => 1,'parent'=>$parent, 'son'=>$son ,'question_list'=>$question_list]));
    }

    /**
     * [trim_array_element description]
     * @Author don
     * @Date   2021-12-22
     * @param  [type]     $array [description]
     * @return [type]            [description]
     */
    private function trim_array_element($array)
    {
        $data = [];
        foreach ($array as $key => $value) {
            $data[] = trim($value);
        }

        return $data;
    }

}
